<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['mapp:mark:add']">
          {{ $t('common.add') }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['mapp:mark:edit']">
          {{ $t('common.edit') }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['mapp:mark:remove']">
          {{ $t('common.delete') }}
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"/>
    </el-row>
    <el-table v-loading="loading" :data="listList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column :label="$t('iot.customer')" align="center" prop="nickName" width="155" show-overflow-tooltip/>
      <el-table-column :label="$t('iot.project')" align="center" prop="projectname" width="155" show-overflow-tooltip/>
      <el-table-column :label="$t('scenicSpot.scenicSpotName')" align="center" prop="name" />
      <el-table-column :label="$t('scenicSpot.deviceId')" align="center" prop="deviceId" show-overflow-tooltip/>
      <el-table-column :label="$t('scenicSpot.belongType')" prop="type" align="center" width="139">
        <template slot-scope="scope">
          <dict-tag :options="translatedDictOptions" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column :label="$t('scenicSpot.yCoordinate')" align="center" prop="lat" />
      <el-table-column :label="$t('scenicSpot.xCoordinate')" align="center" prop="lng" />
      <el-table-column :label="$t('scenicSpot.mp3BroadcastAddress')" align="center" prop="mp3Addr" width="165" show-overflow-tooltip/>
      <el-table-column :label="$t('scenicSpot.scenicSpotIntroduction')" align="center" prop="info" width="165" show-overflow-tooltip/>
      <el-table-column :label="$t('common.operation')" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['mapp:mark:edit']">
            {{ $t('common.edit') }}
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['mapp:mark:remove']">
            {{ $t('common.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList"/>
    <el-dialog :title="title" :visible.sync="open" width="1280px" append-to-body>
      <div class="scrollable-content">
        <el-form ref="form" :model="form" :rules="rules" label-width="178px">
          <el-form-item :label="$t('iot.customerName')" prop="customerId">
            <el-select v-model="form.customerId" :placeholder="$t('iot.selectCustomerName')" filterable style="width:100%" @change="handleNicknameChange">
              <el-option v-for="item in options" :key="item.userId" :label="item.nickName" :value="item.userId"/>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('iot.projectName')" prop="projectId">
            <el-select v-model="form.projectId" :placeholder="$t('iot.selectProjectName')" filterable style="width:100%" @change="handleProjectnameChange">
              <el-option v-for="item in projectnameOptions" :key="item.id" :label="item.projectname" :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('scenicSpot.scenicSpotName')" prop="name">
            <el-input v-model="form.name" :placeholder="$t('scenicSpot.enterScenicSpotName')" />
          </el-form-item>
          <el-form-item :label="$t('scenicSpot.deviceId')" prop="deviceId">
            <el-input v-model="form.deviceId" :placeholder="$t('scenicSpot.enterDeviceId')" />
          </el-form-item>
          <el-form-item :label="$t('scenicSpot.belongType')" prop="type">
            <el-select v-model="form.type" :placeholder="$t('scenicSpot.selectBelongType')" filterable style="width:100%">
              <el-option v-for="dict in translatedDictOptions" :key="dict.value" :label="dict.label" :value="dict.value"/>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('scenicSpot.scenicSpotIcon')" prop="icon">
            <imgUpload v-model="form.icon" style="width:100%"/>
          </el-form-item>
          <el-form-item :label="$t('scenicSpot.yCoordinate')" prop="lat">
            <el-input v-model="form.lat" :placeholder="$t('scenicSpot.enterYCoordinate')" />
          </el-form-item>
          <el-form-item :label="$t('scenicSpot.xCoordinate')" prop="lng">
            <el-input v-model="form.lng" :placeholder="$t('scenicSpot.enterXCoordinate')" />
          </el-form-item>
          <el-form-item :label="$t('scenicSpot.scenicSpotIntroduction')" prop="info">
            <el-input v-model="form.info" :placeholder="$t('scenicSpot.enterIntroduction')" />
          </el-form-item>
          <el-form-item :label="$t('scenicSpot.scenicSpotDetails')">
            <editor v-model="form.listImg" :min-height="192" />
          </el-form-item>
          <el-form-item :label="$t('scenicSpot.mp3BroadcastFile')" prop="mp3Addr">
            <audiooUpload v-model="form.mp3Addr" style="width:100%"/>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{ $t('common.confirm') }}</el-button>
        <el-button @click="cancel">{{ $t('common.cancel') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listList, getList, delList, addList, updateList } from "@/api/iot/marklist";
import { listUser } from '@/api/iot/tool'
import { listProject } from '@/api/iot/faproject'

export default {
  dicts: ['mark_typee'],
  name: "Listt",
  data() {
    return {
      options: [],
      projectnameOptions: [],
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      listList: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        deviceId: null,
        lat: null,
        lng: null,
        icon: null,
        color: null,
        type: null,
        htmlData: null,
        info: null,
        listImg: null,
        mp3Addr: null
      },
      form: {},
      rules: {
        customerId: [{ required: true, message: this.$t('scenicSpot.customerNameRequired'), trigger: "blur" }],
        projectId: [{ required: true, message: this.$t('scenicSpot.projectNameRequired'), trigger: "blur" }],
      }
    };
  },
  computed: {
    currentLanguage() {
      return this.$store.getters.language || 'zh'
    },
    // 计算属性：翻译后的字典选项
    translatedDictOptions() {
      if (!this.dict || !this.dict.type || !this.dict.type.mark_typee) {
        return []
      }
      return this.dict.type.mark_typee.map(dict => ({
        ...dict,
        label: this.getTranslatedTitle(dict)
      }))
    }
  },
  watch: {
    // 监听语言变化，重新渲染组件
    currentLanguage() {
      this.$forceUpdate()
    }
  },
  created() {
    this.getList();
    this.fetchUsers();
    this.fetchProjectnames();
  },
  methods: {
    handleNicknameChange(selectedId) {
      const selectedOption = this.options.find(option => option.userId === selectedId);
      if (selectedOption) {
        this.form.customerId = selectedOption.userId;
      }
    },
    handleProjectnameChange(selectedId) {
      const selectedOption = this.projectnameOptions.find(option => option.id === selectedId);
      if (selectedOption) {
        this.form.projectId = selectedOption.id;
      } else {
        console.error('No matching data found for value:', selectedId);
      }
    },
    async fetchUsers() {
      try {
        const response = await listUser();
        var resList = response.rows;
        if (response && resList) {
          this.options = resList.map(user => ({
            userId: user.userId,
            nickName: user.nickName
          }));
        }
      } catch (error) {
        console.error('error', error);
      }
    },
    async fetchProjectnames() {
      try {
        const response = await listProject();
        var resList = response.rows;
        if (response && resList) {
          this.projectnameOptions = resList.map(item => ({
            id: item.id,
            projectname: item.projectname,
          }));
          console.log("projectnameOptions", this.projectnameOptions);
        } else {
          console.error('Invalid response format:', response);
        }
      } catch (error) {
        console.error('Error fetching project names:', error);
      }
    },
    getList() {
      this.loading = true;
      listList(this.queryParams).then(response => {
        this.listList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        customerId: null,
        projectId: null,
        id: null,
        name: null,
        deviceId: null,
        zoom: 0,
        lat: null,
        lng: null,
        icon: null,
        color: null,
        type: null,
        htmlData: null,
        info: null,
        listImg: null,
        mp3Addr: null
      };
      this.resetForm("form");
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = this.$t('scenicSpot.addScenicSpot');
    },
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getList(id).then(response => {
        var datarerult = response.data;
        this.form = datarerult;
        var icon = datarerult.icon;
        var mp3Addr = datarerult.mp3Addr;
        // 处理图标路径
        if (icon && icon.includes('/profile')) {
          this.form.icon = icon.substring(icon.indexOf('/profile'));
        } else {
          this.form.icon = icon;
        }
        // 处理MP3路径
        if (mp3Addr && mp3Addr.includes('/profile')) {
          this.form.mp3Addr = mp3Addr.substring(mp3Addr.indexOf('/profile'));
        } else {
          this.form.mp3Addr = mp3Addr;
        }
        // 处理HTML数据
        var listImg = datarerult.listImg;
        if (listImg && listImg.includes(',')) {
          var listImgArray = listImg.split(',');
          var listImgresult = [];
          for (var i = 0; i < listImgArray.length; i++) {
            var item = listImgArray[i];
            if (item && item.includes('/profile')) {
              listImgresult.push(item.substring(item.indexOf('/profile')));
            } else {
              listImgresult.push(item);
            }
          }
          this.form.listImg = listImgresult.join(',');
        } else if (listImg && listImg.includes('/profile')) {
          this.form.listImg = listImg.substring(listImg.indexOf('/profile'));
        } else {
          this.form.listImg = listImg;
        }
        this.open = true;
        this.title = this.$t('scenicSpot.editScenicSpot');
      });
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateList(this.form).then(response => {
              this.$modal.msgSuccess(this.$t('common.editSuccess'));
              this.open = false;
              this.getList();
            });
          } else {
            addList(this.form).then(response => {
              this.$modal.msgSuccess(this.$t('common.addSuccess'));
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm(
        this.$t('scenicSpot.confirmDeleteScenicSpot', { ids: ids }),
        this.$t('navbar.tip'),
        {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        }
      ).then(() => {
        return delList(ids);
      }).then(() => {
        this.getList();
        this.$message({
          type: 'success',
          message: this.$t('common.deleteSuccess')
        });
      }).catch(() => {});
    },
    getTranslatedTitle(dict) {
      if (!dict || !dict.label) {
        return ''
      }
      const title = dict.label
      const chinesePattern = /[\u4e00-\u9fa5]/
      // 如果标题不包含中文字符，说明已经是翻译后的，直接返回
      if (!chinesePattern.test(title)) {
        return title
      }
      try {
        // 使用我们之前定义的菜单映射进行翻译
        const menuKeyMap = {
          '全部': 'system.allMark',
          '景点': 'system.markPoint',
          '出入口': 'system.inOut',
          '便利店': 'system.shops',
          '餐厅': 'system.eats',
          '服务': 'system.service',
          '洗手间': 'system.tolet',
          '停车场': 'system.parts',
        }
        const key = menuKeyMap[title]
        if (key && this.$t) {
          const translated = this.$t(key)
          if (translated !== key) {
            return translated
          }
        }
      } catch (error) {
        console.warn('error:', error)
      }
      return title
    }
  }
};
</script>

<style>
.scrollable-content {
  max-height: 80vh;
  overflow-y: scroll;
  padding-right: 10px;
}
.scrollable-content::-webkit-scrollbar {
  width: 8px;
}
.scrollable-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}
.scrollable-content::-webkit-scrollbar-thumb {
  background: #c0c0c0;
  border-radius: 4px;
}
.scrollable-content::-webkit-scrollbar-thumb:hover {
  background: #a0a0a0;
}
</style>
